package user

import (
	"context"
	"errors"
	"git.mycaigou.com/gfyx/common/authorize"
	userRepo "git.mycaigou.com/gfyx/micro-gfyx-api/infrastructure/repository/base/user"
	"github.com/gin-gonic/gin"
)

type UserService struct {
	userRepo userRepo.UserRepositoryIface
}

// 创建构造函数
func NewUserService(UserRepo userRepo.UserRepositoryIface) UserSerivceIface {
	return &UserService{
		userRepo: UserRepo,
	}
}

func (s *UserService) SsoLogin(ctx *gin.Context, accessToken string) (token string, err error) {
	token, err = s.userRepo.SsoLogin(ctx, accessToken)
	if err != nil {
		return "", err
	}
	return token, nil
}

// 退出登录
func (s *UserService) UserLogout(ctx *gin.Context, token string) error {
	err := s.userRepo.UserLogout(ctx, token)
	if err != nil {
		return err
	}
	authorize.UnsetLoginContext(ctx)
	return nil
}

// 获取用户信息
func (s *UserService) GetUserInfoByGlobalUserId(ctx context.Context, globalUid string) (*userRepo.UserLoginInfo, error) {
	return s.userRepo.GetUserInfo(ctx, &userRepo.GetUserInfoParams{
		GlobalUid: globalUid,
	})
}

// 获取用户信息
func (s *UserService) GetUserInfoByOpenId(ctx context.Context, openId string) (*userRepo.UserLoginInfo, error) {
	return s.userRepo.GetUserInfo(ctx, &userRepo.GetUserInfoParams{OpenId: openId})
}

func (s *UserService) UserLogin(ctx context.Context, tenantCode, account, password string) (*userRepo.UserLoginInfo, error) {
	loginInfo, err := s.userRepo.UserLogin(ctx, tenantCode, account, password)
	if err != nil {
		return nil, err
	}
	if loginInfo == nil {
		return nil, errors.New("登录失败")
	}

	return loginInfo, nil
}

// 验证token
func (s *UserService) VerifyToken(ctx context.Context, token string) (info *userRepo.UserInfo, tenantInfo *userRepo.TenantUnionInfo, err error) {
	return s.userRepo.VerifyToken(ctx, token)
}
